from system.host.models import Group
from django.db.models import F
from system.host.serializers import GroupSerializer, GroupCreateUpdateSerializer, GroupWithHostsSerializer
from utils.viewset import CustomModelViewSet
from utils.json_response import SuccessResponse
import json

new_data = list()


def merge_children(data):
    for item in data:
        item['children'].extend(item['groups'])
        if item['children']:
            merge_children(item)
        new_data.append(item)
    return new_data


def fetch_children(data, with_hosts):
    if data:
        sub_data = dict()
        for item in Group.objects.filter(parent_id__in=data.keys()):
            tmp = item.to_view(with_hosts)
            sub_data[item.id] = tmp
            data[item.parent_id]['children'].append(tmp)
        return fetch_children(sub_data, with_hosts)


class GroupModelViewSet(CustomModelViewSet):
    """
    主机管理 的CRUD视图
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    create_serializer_class = GroupCreateUpdateSerializer
    update_serializer_class = GroupCreateUpdateSerializer

    def list(self, request, *args, **kwargs):
        with_hosts = request.GET.get('with_hosts')
        query_set = Group.objects.filter(parent__id__isnull=True)
        if with_hosts:
            serializer = GroupWithHostsSerializer(query_set, many=True)
        else:
            serializer = GroupSerializer(query_set, many=True)
        return SuccessResponse(data=serializer.data, message="获取成功")

    def partial_update(self, request, *args, **kwargs):
        src = Group.objects.filter(id=kwargs.get('pk')).first()
        if src:
            action = request.data.get('action')
            d_id = request.data.get('d_id')
            dst = Group.objects.get(pk=d_id)
            if action == 0:
                src.parent_id = dst.id
                dst = Group.objects.filter(parent_id=dst.id).first()
                if not dst:
                    src.save()
                    return SuccessResponse(data='', message="更新成功")
                action = -1
            src.parent_id = dst.parent_id
            if src.sort_id > dst.sort_id:
                if action == -1:
                    dst = Group.objects.filter(sort_id__gt=dst.sort_id).last()
                Group.objects.filter(sort_id__lt=src.sort_id, sort_id__gte=dst.sort_id).update(sort_id=F('sort_id') + 1)
            else:
                if action == 1:
                    dst = Group.objects.filter(sort_id__lt=dst.sort_id).first()
                Group.objects.filter(sort_id__lte=dst.sort_id, sort_id__gt=src.sort_id).update(sort_id=F('sort_id') - 1)
            src.sort_id = dst.sort_id
            src.save()
        return SuccessResponse(data='', message="更新成功")
